package com.diy.sigmund.diycommon.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author ylm-sigmund
 * @see <a href="https://blog.csdn.net/aojiexu2568/article/details/101647015">二进制转换工具：</a>
 * @since 2021/10/23 14:26
 */
public class BinaryConversionUtil {

    private static final Logger log = LoggerFactory.getLogger(BinaryConversionUtil.class);

    /**
     * Java将字符串转成二进制码<br>
     * string to binary=[user1]->[1110101 1110011 1100101 1110010 110001 ]<br>
     * string to binary=[小明]->[101110000001111 110011000001110 ]<br>
     */
    public static String stringToBinary(String str) {
        char[] strChar = str.toCharArray();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < strChar.length; i++) {
            result.append(Integer.toBinaryString(strChar[i])).append(" ");
        }
        String strBinary = result.toString();
        log.info("string to binary=[{}]->[{}]", str, strBinary);
        return strBinary;
    }

    /**
     * 将二进制字符串转换成int数组
     */
    public static int[] binaryToIntArray(String binary) {
        char[] temp = binary.toCharArray();
        int[] result = new int[temp.length];
        for (int i = 0; i < temp.length; i++) {
            result[i] = temp[i] - 48;
        }
        return result;
    }

    /**
     * 将二进制转换成字符
     */
    public static char binaryToChar(String binary) {
        int[] temp = binaryToIntArray(binary);
        int sum = 0;
        for (int i = 0; i < temp.length; i++) {
            sum += temp[temp.length - 1 - i] << i;
        }
        return (char) sum;
    }

    /**
     * 将二进制转换成字符串<br>
     * binary to string=[1110101 1110011 1100101 1110010 110001 ]->[user1]<br>
     * binary to string=[101110000001111 110011000001110 ]->[小明]<br>
     */
    public static String binaryToString(String binary) {
        String[] tempStr = binary.split(" ");
        char[] tempChar = new char[tempStr.length];
        for (int i = 0; i < tempStr.length; i++) {
            tempChar[i] = binaryToChar(tempStr[i]);
        }
        String str = String.valueOf(tempChar);
        log.info("binary to string=[{}]->[{}]", binary, str);
        return str;
    }
}
